import { Request, Response } from 'express';
import { FriendInput, ContactInput } from "../schemas/friend.schemas";
import friendService from '../services/friend.service';
import userService from '../services/user.service';
import groupService from '../services/group.service';
import { sendUserMessage } from '../websocket/process';

class FriendController {
    async getFriend(req: Request, res: Response) {
        const { userId } = req.auth;
        const { friendId } = req.query as FriendInput;

        const friendInfo = await userService.findUserByUserId(friendId)
        if (!friendInfo || friendInfo.status === 'BANNED') {
            res.status(400).json({ message: 'user not found' });
            return
        }

        const userFriend = await friendService.getUserFriend(userId, friendId);
        res.send({
            ...friendInfo,
            isFriend: !!userFriend
        });
    }

    async getContact(req: Request, res: Response) {
        const { userId } = req.auth;
        const { contactId } = req.query as ContactInput;

        // 首先搜索好友
        let contactInfo = null;
        let isFrined = false;
        let isMember = false;

        contactInfo = await userService.findUserByUserId(contactId)
        if (!contactInfo || contactInfo.status === 'BANNED') {
            // 接着搜索群聊
            contactInfo = await groupService.getGroup(contactId);
            if (!contactInfo || contactInfo.status === 'DISBAND') {
                res.status(400).json({ message: '没有搜索到结果' });
                return
            }else{
                // 检查是否是群成员
                isMember = contactInfo.members.findIndex(member => member.userId === userId) !== -1;
            }
        }else{
            // 检查是否是好友
            const userFriend = await friendService.getUserFriend(userId, contactId);
            isFrined = !!userFriend;
        }

        res.send({
            ...contactInfo,
            isFriend: isFrined,
            isMember: isMember
        });
    }

    async deleteFriend(req: Request, res: Response) {
        const { userId } = req.auth;
        const { friendId } = req.query as FriendInput;

        const userFriend = await friendService.getUserFriend(userId, friendId);
        if (!userFriend) {
            res.status(400).json({ message: 'you are not friend' })
            return
        }

        const friend = await friendService.removeFriend(userId, friendId);
        sendUserMessage('contact', friend, userId);
        res.send({ message: 'delete success' })
    }

}
const friendController = new FriendController();
export default friendController;